import { useState, useEffect } from 'react';
import Nabar from '../../conpoment/Nabar';
import styles from './index.module.css';
import { useNavigate } from 'react-router-dom';

// 预约数据接口
interface AppointmentData {
  id: string;
  doctorName: string;
  doctorTitle: string;
  department: string;
  hospital: string;
  patientName: string;
  appointmentTime: string;
  timeSlot: string;
  status: 'pending' | 'completed';
  canRetrieveTime?: string;
  doctorAvatar?: string;
  queueNumber?: number;
  appointmentNumber?: string;
  consultationLocation?: string;
}

function Index() {
  const [activeTab, setActiveTab] = useState<'pending' | 'completed'>('completed');
  const [currentTime, setCurrentTime] = useState(new Date());
  const [appointments, setAppointments] = useState<AppointmentData[]>([
    {
      id: '1',
      doctorName: '刘医生',
      doctorTitle: '主任医师',
      department: '门诊外一科',
      hospital: '四川省保健院南苑',
      patientName: '王小柯',
      appointmentTime: '2020-01-27 08:30-12:00',
      timeSlot: '上午',
      status: 'completed',
      doctorAvatar: '👨‍⚕️',
      queueNumber: 20,
      appointmentNumber: '20200101020',
      consultationLocation: '南苑门诊大楼二楼520诊室'
    },
    {
      id: '2',
      doctorName: '张医生',
      doctorTitle: '主任医师',
      department: '口腔科',
      hospital: '四川省保健院南苑',
      patientName: '王小柯',
      appointmentTime: '2020-01-27 14:30-17:00',
      timeSlot: '下午',
      status: 'pending',
      canRetrieveTime: '下午13:30-17:00可取号',
      doctorAvatar: '👩‍⚕️'
    },
    {
      id: '3',
      doctorName: '李医生',
      doctorTitle: '副主任医师',
      department: '内科',
      hospital: '四川省保健院南苑',
      patientName: '王小柯',
      appointmentTime: '2020-01-28 09:00-11:30',
      timeSlot: '上午',
      status: 'pending',
      doctorAvatar: '👨‍⚕️',
      queueNumber: 15,
      appointmentNumber: '20200102015',
      consultationLocation: '南苑门诊大楼三楼310诊室'
    }
  ]);
  // 根据状态过滤预约记录
  const filteredAppointments = appointments.filter(appointment =>
    appointment.status === activeTab
  );
  const nav = useNavigate();
  // 获取当前时间状态信息
  const getTimeStatusInfo = () => {
    const currentHour = currentTime.getHours();
    const currentMinute = currentTime.getMinutes();
    const currentTimeInMinutes = currentHour * 60 + currentMinute;
    const startTime = 13 * 60 + 30; // 13:30
    const endTime = 17 * 60; // 17:00
    if (currentTimeInMinutes < startTime) {
      const hoursLeft = Math.floor((startTime - currentTimeInMinutes) / 60);
      const minutesLeft = (startTime - currentTimeInMinutes) % 60;
      return {
        canRetrieve: false,
        message: `取号时间未到，请于13:30-17:00取号`,
        timeLeft: startTime - currentTimeInMinutes,
        timeLeftText: hoursLeft > 0 ? `还需等待${hoursLeft}小时${minutesLeft}分钟` : `还需等待${minutesLeft}分钟`
      };
    } else if (currentTimeInMinutes > endTime) {
      return {
        canRetrieve: false,
        message: `取号时间已过，请于13:30-17:00取号`,
        timeLeft: 0,
        timeLeftText: ''
      };
    } else {
      const hoursLeft = Math.floor((endTime - currentTimeInMinutes) / 60);
      const minutesLeft = (endTime - currentTimeInMinutes) % 60;
      return {
        canRetrieve: true,
        message: `下午13:30-17:00可取号`,
        timeLeft: endTime - currentTimeInMinutes,
        timeLeftText: `剩余${hoursLeft}小时${minutesLeft}分钟`
      };
    }
  };
  // 页面加载时检查是否有新的取号数据
  useEffect(() => {
    const retrievedData = sessionStorage.getItem('retrievedAppointment');
    if (retrievedData) {
      try {
        const newAppointment = JSON.parse(retrievedData);
        // 生成新的ID
        const newId = Date.now().toString();
        const appointmentToAdd = {
          ...newAppointment,
          id: newId,
          status: 'completed' as const
        };
        // 添加到预约列表
        setAppointments(prev => [appointmentToAdd, ...prev]);
        // 清除sessionStorage中的数据
        sessionStorage.removeItem('retrievedAppointment');
        // 切换到已取号标签页
        setActiveTab('completed');
      } catch (error) {
        console.error('解析取号数据失败:', error);
      }
    }
  }, []);

  // 实时更新时间
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000); // 每秒更新一次

    return () => clearInterval(timer);
  }, []);
  const handleRetrieveNumber = (appointmentId: string) => {
    console.log('取号:', appointmentId);
    // 这里可以添加取号逻辑
    // 成功后可以更新状态或跳转
    nav('/self-service-num');
  };
  return (
    <div className={styles.container}>
      {/* 顶部导航栏 */}
      <Nabar title="自助取号" sticky={false} />
      {/* 用户信息栏 */}
      <div className={styles.userInfo}>
        <div className={styles.userDetails}>
          <span className={styles.userName}>王小柯</span>
          <span className={styles.userId}>2015****10</span>
        </div>
        <div className={styles.switchButton}>
          <span className={styles.switchIcon}>👥</span>
          <span className={styles.switchText}>切换</span>
        </div>
      </div>
      {/* 标签页 */}
      <div className={styles.tabContainer}>
        <div
          className={`${styles.tab} ${activeTab === 'pending' ? styles.activeTab : ''}`}
          onClick={() => setActiveTab('pending')}
        >
          待取号
        </div>
        <div
          className={`${styles.tab} ${activeTab === 'completed' ? styles.activeTab : ''}`}
          onClick={() => setActiveTab('completed')}
        >
          已取号
        </div>
      </div>
      {/* 预约卡片列表 */}
      <div className={styles.appointmentList}>
        {filteredAppointments.map((appointment) => (
          <div key={appointment.id} className={styles.appointmentCard}>
            {/* 医生信息 */}
            <div className={styles.doctorInfo}>
              <div className={styles.doctorAvatar}>
                {appointment.doctorAvatar}
              </div>
              <div className={styles.doctorDetails}>
                <div className={styles.doctorName}>{appointment.doctorName}</div>
                <div className={styles.doctorTitle}>{appointment.doctorTitle}</div>
                <div className={styles.department}>{appointment.department}</div>
                <div className={styles.hospital}>{appointment.hospital}</div>
              </div>
            </div>
            {/* 患者和时间信息 */}
            <div className={styles.appointmentDetails}>
              <div className={styles.detailRow}>
                <span className={styles.label}>就诊人</span>
                <span className={styles.value}>{appointment.patientName}</span>
              </div>
              {appointment.appointmentNumber && (
                <div className={styles.detailRow}>
                  <span className={styles.label}>预约号</span>
                  <span className={styles.value}>{appointment.appointmentNumber}</span>
                </div>
              )}
              <div className={styles.detailRow}>
                <span className={styles.label}>预约时间</span>
                <span className={styles.value}>
                  {appointment.appointmentTime} ({appointment.timeSlot})
                </span>
              </div>
              {appointment.consultationLocation && (
                <div className={styles.detailRow}>
                  <span className={styles.label}>就诊地点</span>
                  <span className={styles.value}>{appointment.consultationLocation}</span>
                </div>
              )}
            </div>
            {/* 排队号显示 */}
            {appointment.status === 'completed' && appointment.queueNumber && (
              <div className={styles.queueSection}>
                <div className={styles.queueNumber}>
                  排队号: {appointment.queueNumber}
                </div>
              </div>
            )}
            {/* 操作按钮或信息 */}
            <div className={styles.actionArea}>
              {appointment.status === 'pending' ? (
                (() => {
                  const timeStatus = getTimeStatusInfo();
                  if (timeStatus.canRetrieve) {
                    return (
                      <button
                        className={styles.retrieveButton}
                        onClick={() => handleRetrieveNumber(appointment.id)}
                      >
                        去取号
                      </button>
                    );
                  } else {
                    return (
                      <div className={`${styles.timeInfo} ${styles.disabled}`}>
                        <div>{timeStatus.message}</div>
                        {timeStatus.timeLeftText && (
                          <div style={{ fontSize: '12px', marginTop: '4px', opacity: 0.8 }}>
                            {timeStatus.timeLeftText}
                          </div>
                        )}
                      </div>
                    );
                  }
                })()
              ) : (
                <div className={styles.completedInfo}>
                  已取号
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
export default Index;